package cn.vivi35.downloadprovider.app;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

/**
 * 
 * 下载管理器的辅助类，用来获取当前下载的文件（下载中、已下载等状态）
 * 
 * 注意：
 * getFileXXX 这个file指的是下载的文件，
 * filename指的是文件名，但不包括绝对路径；绝对路径一般命名为absFilename
 * 
 * @author Vivi Peng
 * 
 */
public class DownloadManagerHelper {

	/**
	 * 通过id获取DownloadManagerFile
	 * 
	 * @param context
	 * @param id
	 * @return
	 */
	public static final DownloadManagerFile findFileById(Context context, long id) {
		if (id < 0) {
			return null;
		}
		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterById(id);
		Cursor c = manager.query(query);
		if (c != null) {
			while (c.moveToNext()) {
				DownloadManagerFile tmpFile = DownloadManagerFile.newInstance(c);
				return tmpFile;

			}
			c.close();
		}

		return null;
	}


	/**
	 * 通过文件名获取DownloadManagerFile
	 * 
	 * @param context
	 * @param filename
	 * @return
	 */
	public static final DownloadManagerFile findFileByFilename(Context context, String filename) {
		if (TextUtils.isEmpty(filename)) {
			return null;
		}
		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());
		DownloadManager.Query query = new DownloadManager.Query();
		Cursor c = manager.query(query);
		if (c != null) {
			while (c.moveToNext()) {
				DownloadManagerFile tmpFile = DownloadManagerFile.newInstance(c);
				if (!TextUtils.equals(tmpFile.getFileName(), filename)) {
					return tmpFile;
				}

			}
			c.close();
		}

		return null;
	}


	/**
	 * 通过文件的url来查找DownloadManagerFile
	 * 
	 * @param context
	 * @param url
	 * @return
	 */
	public static final DownloadManagerFile findFileByUrl(Context context, String url) {
		DownloadManagerFile retFile = null;
		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());

		DownloadManager.Query query = new DownloadManager.Query();
		Cursor c = manager.query(query);
		if (c != null) {
			String tempUri = null;
			while (c.moveToNext()) {
				tempUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
				if (!TextUtils.isEmpty(tempUri) && tempUri.equals(url)) {
					retFile = DownloadManagerFile.newInstance(c);
					break;
				}

			}
			c.close();
		}

		return retFile;
	}


	/**
	 * 通过文件名查询正在下载的DownloadManagerFile
	 * 
	 * @param context
	 * @param filename
	 * @return
	 */
	public static DownloadManagerFile findLoadingFileByFilename(Context context, final String filename) {
		if (TextUtils.isEmpty(filename)) {
			return null;
		}

		DownloadManagerFile retFile = null;
		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterByStatus(DownloadManager.STATUS_RUNNING);
		Cursor c = manager.query(query);
		if (c != null) {
			while (c.moveToNext()) {
				DownloadManagerFile tmpFile = DownloadManagerFile.newInstance(c);
				if (TextUtils.equals(filename, tmpFile.getFileName())) {
					retFile = tmpFile;
					break;
				}

			}
			c.close();
		}

		return retFile;
	}


	/**
	 * 通过id查询正在下载的DownloadManagerFile
	 * 
	 * @param context
	 * @param id
	 * @return
	 */
	public static DownloadManagerFile findLoadingFileById(Context context, final long id) {
		if (id < 0) {
			return null;
		}

		DownloadManagerFile retFile = null;
		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterById(id);
		query.setFilterByStatus(DownloadManager.STATUS_RUNNING);
		Cursor c = manager.query(query);
		if (c != null) {
			while (c.moveToNext()) {
				DownloadManagerFile tmpFile = DownloadManagerFile.newInstance(c);
				return tmpFile;
			}
			c.close();
		}

		return retFile;
	}


	/**
	 * 获取所有处于“下载中”状态的文件
	 * 
	 * @param context
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesInLoadding(Context context) {
		return findAllFilesOfStatus(context, null, -1, DownloadManager.STATUS_RUNNING);
	}


	/**
	 * 获取所有处于“暂停”状态的文件
	 * 
	 * @param context
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesPaused(Context context) {
		return findAllFilesOfStatus(context, null, -1, DownloadManager.STATUS_PAUSED);
	}


	/**
	 * 获取所有处于“准备中”状态的文件
	 * 
	 * @param context
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesPending(Context context) {
		return findAllFilesOfStatus(context, null, -1, DownloadManager.STATUS_PENDING);
	}


	/**
	 * 获取所有处于“下载失败”状态的文件
	 * 
	 * @param context
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesFailed(Context context) {
		return findAllFilesOfStatus(context, null, -1, DownloadManager.STATUS_FAILED);
	}


	/**
	 * 获取所有处于“下载成功”状态的文件
	 * 
	 * 注意：下载成功表示的是一个状态，并不保证下载成功的文件不被删除
	 * 
	 * @param context
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesDownSucc(Context context) {
		return findAllFilesOfStatus(context, null, -1, DownloadManager.STATUS_SUCCESSFUL);
	}


	/**
	 * 查找所有指定的文件，用户可以通过“文件状态”来过滤自己想要的文件。 不传参数则默认查询所有状态
	 * 
	 * @param context
	 * @param status
	 *            DownloadManager.STATUS_FAILED DownloadManager.STATUS_PAUSED DownloadManager.STATUS_PENDING
	 *            DownloadManager.STATUS_RUNNING DownloadManager.STATUS_SUCCESSFUL
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesOfStatus(Context context, Integer... status) {
		return findAllFilesOfStatus(context, null, -1, status);
	}


	/**
	 * 查找所有指定的文件，用户可以通过“文件状态”来过滤自己想要的文件。
	 * 同时用户还可以选择根据某个column来排序。
	 * e.g findAllFilesOfStatus(context, DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP,
	 * DownloadManager.Query.ORDER_DESCENDING, status)
	 * 
	 * @param context
	 * @param column
	 * @param direction
	 * @param status
	 * @return
	 */
	public static List<DownloadManagerFile> findAllFilesOfStatus(Context context, String column,
			int direction, Integer... status) {
		int state = -1;
		if (status != null && status.length > 0) {
			state = 0;
			for (Integer tmpState : status) {
				state |= tmpState;
			}
		}
		return findAllFilesOfStatus(context, column, direction, state);
	}


	private static List<DownloadManagerFile> findAllFilesOfStatus(Context context, String column,
			int direction, int status) {
		List<DownloadManagerFile> retFiles = new ArrayList<DownloadManagerFile>();
		DownloadManager.Query query = new DownloadManager.Query();
		// 如果为-1等负值，则返回所有的数据
		if (status > 0) {
			query.setFilterByStatus(status);
		}

		// 排序
		if (!TextUtils.isEmpty(column)) {
			query.orderBy(column, direction);
		}

		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());
		Cursor c = manager.query(query);
		if (c != null) {
			while (c.moveToNext()) {
				DownloadManagerFile tmpFile = DownloadManagerFile.newInstance(c);
				retFiles.add(tmpFile);

			}
			c.close();
		}

		return retFiles;
	}


	/*public static long requestDownloadFile(Context context, String url, String destName, String filename) {
		// 如果没有sdcard就不下载了
		if (!FileManager.isSdcardAvalible()) {
			Log.w("DownloadHelper", "Sdcard is unmounted or not writable");
			Toast.makeText(context, "亲，找不到手机的SD卡！", Toast.LENGTH_LONG).show();
			return -2;
		}

		if (NetUtils.getNetworkStatus(context) == NetUtils.NETWORK_STATE_IDLE) {
			Toast.makeText(context, "亲，没有网络哦！", Toast.LENGTH_LONG).show();
			return -3;
		}

		SLog.d("Download", "url == " + url);

		String downlaodPath = null;
		try {
			downlaodPath = FileManager.getApksDownloadPath();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			return -2;
		}

		File file = new File(downlaodPath, destName);
		if (file.exists()) {
			file.delete();
		}

		Uri resource = Uri.parse(url);
		try {
			DownloadManager downloadManager = (DownloadManager) context
					.getSystemService(Context.DOWNLOAD_SERVICE);
			DownloadManager.Request request = new DownloadManager.Request(resource);
			request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
			request.setAllowedOverRoaming(false);
			request.setShowRunningNotification(true);
			request.setVisibleInDownloadsUi(true);
			// sdcard的目录下的download文件夹
			// FileManager.getApksDownloadPath();
			String sdcardDir = FileManager.DIR_DOWNLOAD_APK_PATH;
			request.setDestinationInExternalPublicDir(sdcardDir, destName);

			request.setTitle(filename);
			Toast.makeText(context, "亲，开始下载" + filename.trim() + "了！", Toast.LENGTH_SHORT).show();
			return downloadManager.enqueue(request);

		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, "请打开应用列表中下载及下载管理器程序，以确保正常下载！", Toast.LENGTH_SHORT).show();
			return -2;
		}

	}*/

	public static final void clearDownloadLog(Context context, long clearId) {
		DownloadManager manager = new DownloadManager(context.getContentResolver(), context.getPackageName());
		DownloadManager.Query query = new DownloadManager.Query();
		if (clearId > 0) {
			query.setFilterById(clearId);
		}
		Cursor c = manager.query(query);
		if (c != null) {
			while (c.moveToNext()) {
				long id = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID));
				manager.remove(id);
			}
		}

		c.close();
	}

}
